package com.recipedb.recipedb.controller;

import com.recipedb.recipedb.entity.UserBrowse;
import com.recipedb.recipedb.entity.Recipe;
import com.recipedb.recipedb.service.UserBrowseService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.data.domain.Page;
import com.recipedb.recipedb.service.UserService;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;

import java.util.List;

@RestController
@RequestMapping("/api/browse")
@RequiredArgsConstructor
public class UserBrowseController {

    private final UserBrowseService userBrowseService;
    private final UserService userService;

    @PostMapping
    public ResponseEntity<UserBrowse> createBrowseRecord(
            @RequestParam Long userId,
            @RequestParam Long recipeId) {
        UserBrowse browseRecord = userBrowseService.createBrowseRecord(userId, recipeId);
        return ResponseEntity.ok(browseRecord);
    }


    @GetMapping("/user/{userId}")
    public ResponseEntity<List<UserBrowse>> getBrowseRecordsByUserId(@PathVariable Long userId) {
        List<UserBrowse> browseRecords = userBrowseService.getBrowseRecordsByUserId(userId);
        return ResponseEntity.ok(browseRecords);
    }

    @GetMapping
    public ResponseEntity<List<UserBrowse>> getAllBrowseRecords() {
        List<UserBrowse> browseRecords = userBrowseService.getAllBrowseRecords();
        return ResponseEntity.ok(browseRecords);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteBrowseRecord(
            @PathVariable Long id,
            @RequestParam Long userId) {
        boolean deleted = userBrowseService.deleteBrowseRecord(id, userId);
        if (deleted) {
            return ResponseEntity.ok().body("浏览记录删除成功");
        } else {
            return ResponseEntity.badRequest().body("浏览记录删除失败，记录不存在或无权删除");
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<UserBrowse> getBrowseRecordById(@PathVariable Long id) {
        return userBrowseService.getBrowseRecordById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @GetMapping("/user/{userId}/recipe/{recipeId}")
    public ResponseEntity<UserBrowse> getBrowseRecordByUserAndRecipe(
            @PathVariable Long userId,
            @PathVariable Long recipeId) {
        return userBrowseService.getBrowseRecordByUserIdAndRecipeId(userId, recipeId)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @GetMapping("/user/{userId}/recipes")
    public ResponseEntity<List<Recipe>> getRecipesByUserId(@PathVariable Long userId) {
        List<Recipe> recipes = userBrowseService.getRecipesByUserId(userId);
        return ResponseEntity.ok(recipes);
    }

    // ========== 核心：浏览记录搜索接口（和收藏搜索接口对齐） ==========
    @GetMapping("/user/{userId}/search")
    public ResponseEntity<Page<UserBrowse>> searchBrowseRecords(
            @PathVariable Long userId,
            @RequestParam(required = false) String keyword,  // 核心单参数
            @RequestParam(required = false) String tag,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String ingredient,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            Authentication authentication) {

        // 1. 校验是否已登录
        if (authentication == null || !authentication.isAuthenticated()) {
            throw new AccessDeniedException("请先登录后再查询浏览记录");
        }

        // 2. 解析Token对应的真实登录用户ID
        String loginUsername = authentication.getName();
        Long loginUserId = userService.getUserIdByUsername(loginUsername);
        if (loginUserId == null) {
            throw new AccessDeniedException("登录用户不存在");
        }

        // 3. 严格校验：只能查询自己的浏览记录
        if (!loginUserId.equals(userId)) {
            throw new AccessDeniedException("无权查询用户" + userId + "的浏览记录");
        }

        Page<UserBrowse> result = userBrowseService.searchBrowseRecords(
                userId,
                keyword,
                tag,
                category,
                ingredient,
                pageNum,
                pageSize
        );
        return ResponseEntity.ok(result);
    }
}